<template>
  <div>
    <!-- 条件搜索表单项 -->
    <div class="searchDiv">
      <div>
        <el-form :inline="true">
          <el-form-item label="关键字">
            <el-input
              v-model="searchObj.keyword"
              placeholder="用户名、姓名、手机号"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="date"
              type="daterange"
              :unlink-panels="true"
              value-format="YYYY-MM-DD"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="截止时间"
              :size="size"
            />
          </el-form-item>
        </el-form>
      </div>
      <div style="margin: 10px;">
        <el-button type="primary" size="small" @click="fetchData">
          搜索
        </el-button>
        <el-button size="small" @click="handleReset">重置</el-button>
      </div>
      <!-- 添加按钮 -->
      <div class="tools-div">
        <hr />
        <el-button type="success" size="small" @click="handleShowAddDialog">
          添 加
        </el-button>
        <hr />
      </div>
    </div>
    <!-- 展示分页数据的表格 -->
    <div>
      <el-table :data="users" stripe style="width: 100%">
        <el-table-column prop="username" label="用户名称" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="phone" label="手机号码" />
        <el-table-column prop="avatar" label="头像" #default="scope">
          <img :src="scope.row.avatar" style="height:40px;width:40px;" />
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="phone" label="状态" #default="scope">
          <el-tag v-if="scope.row.status === 1">正常</el-tag>
          <el-tag v-else type="danger">锁定</el-tag>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleShowEditDialog(scope.row)">
              修改
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <el-button
              size="small"
              @click="handleShowRoleDialog(scope.row)"
              style="width: 75px;"
            >
              分配角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页导航 -->
    <div style="margin-top: 80px;">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[1, 2, 3, 4, 5]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="fetchData"
        @current-change="fetchData"
      />
    </div>
    <!-- 新增/更新用户的对话框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加或修改用户">
        <el-form>
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <el-input v-model="user.username" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="密码"
            v-if="!user.id"
            :label-width="formLabelWidth"
          >
            <el-input v-model="user.password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="姓名" :label-width="formLabelWidth">
            <el-input v-model="user.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="手机" :label-width="formLabelWidth">
            <el-input v-model="user.phone" autocomplete="off" />
          </el-form-item>
          <el-form-item label="头像" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :action="uploadPath"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :headers="headers"
              name="file"
              :data="{ module: 'avatar' }"
            >
              <img v-if="user.avatar" :src="user.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item label="描述" :label-width="formLabelWidth">
            <el-input v-model="user.description" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveOrUpdateUser">
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <div>
      <el-dialog v-model="dialogVisible" title="分配角色">
        <el-form>
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <el-input :value="user.name" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="角色列表" :label-width="formLabelWidth">
            <el-checkbox-group v-model="checkedRoleIds">
              <el-checkbox
                v-for="role in roles"
                :key="role.id"
                :label="role.id"
                :checked="role.checked"
              >
                {{ role.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="handleAssignRole">
            提交
          </el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  GetSysUserPage,
  DeleteUserById,
  GetUserById,
  UpdateUserById,
  SaveUser,
} from '@/api/sysUser'
import { useApp } from '@/pinia/modules/app'
import { getRoles, AssignRoles2User } from '@/api/sysRole'

const users = ref([])
const roles = ref([])
const role = ref({})
const checkedRoleIds = ref([])
const user = ref({})
const pageNum = ref(1)
const pageSize = ref(3)
const total = ref(0)
const searchObj = ref({})
const date = ref()
const dialogFormVisible = ref(false)
const dialogVisible = ref(false)
const formLabelWidth = '120px'
const uploadPath = 'http://localhost:8501/admin/file/upload'
const headers = {
  token: useApp().authorization.token,
}

onMounted(() => {
  fetchData()
})

const handleDelete = row => {
  ElMessageBox.confirm(
    `正在删除用户【${row.username}】 ,是否确认?`,
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await DeleteUserById(row.id)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      //刷新页面数据
      fetchData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const handleSaveUser = async () => {
  await SaveUser(user.value)
  dialogFormVisible.value = false
  ElMessage.success('添加成功')
  fetchData()
}
const handleShowAddDialog = async () => {
  user.value = {}
  dialogFormVisible.value = true
}
const handleShowEditDialog = async row => {
  user.value = {}
  const { data } = await GetUserById(row.id)
  user.value = data
  dialogFormVisible.value = true
}
const handleUpdateUser = async () => {
  await UpdateUserById(user.value)
  ElMessage.success('修改成功')
  dialogFormVisible.value = false
  fetchData()
}
const handleSaveOrUpdateUser = () => {
  if (user.value.id) {
    handleUpdateUser()
  } else {
    handleSaveUser()
  }
}

const handleReset = () => {
  searchObj.value = {}
  pageNum.value = 1
  pageSize.value = 3
  date.value = []
  fetchData()
}

const handleAvatarSuccess = (response, uploadFile) => {
  if (+response.code === 200) {
    console.log(response, uploadFile)

    user.value.avatar = response.data
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error('文件上传失败')
  }
}
const handleAvatarError = (error, uploadFile) => {
  console.log(error, uploadFile)
  ElMessage.error('文件服务器网络连接失败')
}

const handleShowRoleDialog = async row => {
  checkedRoleIds.value = []
  roles.value = []
  user.value = row
  const { data, code } = await getRoles(row.id)
  roles.value = data
  dialogVisible.value = true
}

const handleAssignRole = async () => {
  console.log(checkedRoleIds.value)
  await AssignRoles2User(user.value.id, checkedRoleIds.value)

  ElMessage.success('角色分配成功')
  dialogVisible.value = false
}

const fetchData = async () => {
  console.log(searchObj.value, date.value)
  if (date.value && date.value.length === 2) {
    searchObj.value.beginDate = date.value[0]
    searchObj.value.endDate = date.value[1]
  }
  console.log(searchObj.value)
  const { data } = await GetSysUserPage(
    pageNum.value,
    pageSize.value,
    searchObj.value
  )
  total.value = data.total
  users.value = data.list
}
</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
